from rest_framework import serializers
from goods.models import SKU, SKUSpecification, GoodsCategory, SPU, SPUSpecification, SpecificationOption


class SKUSpecificationSerializer(serializers.ModelSerializer):
    '''
    SKU具体规格表序列化器
    '''

    class Meta:
        model = SKUSpecification
        fields = ('spec_id', 'option_id')


class SKUSerializer(serializers.ModelSerializer):
    # 根据外键拿到关联的spu和category的names属性
    spu = serializers.StringRelatedField(read_only=True)
    category = serializers.StringRelatedField(read_only=True)
    # 通过对象拿到id
    spu_id = serializers.IntegerField()
    category_id = serializers.IntegerField()

    # SKUSPEC表关联SKU 所以进行反向查询用SKUSPEC的releted_name ：specs
    specs = SKUSpecificationSerializer(many=True)

    class Meta:
        model = SKU
        fields = '__all__'

    # 由于sku表中没有specs字段，所以在反序列化过程是需要重写create方法
    # 进行对sku和skus两个表的储存
    def create(self, validated_data):
        # 对sku表进行数据储存
        specs = self.context['request'].data.get('specs')
        del validated_data['specs']
        sku = SKU.objects.create(**validated_data)
        # 对skus表进行储存
        for spec in specs:
            SKUSpecification.objects.create(sku=sku, spec_id=spec['spec_id'], option_id=spec['option_id'])
        return sku

    def update(self, instance, validated_data):
        # 对sku表进行数据储存
        specs = self.context['request'].data.get('specs')
        instance.market_price = validated_data['market_price']
        instance.stock = validated_data['stock']
        instance.is_launched = validated_data['is_launched']
        instance.cost_price = validated_data['cost_price']
        instance.price = validated_data['price']
        instance.caption = validated_data['caption']
        instance.name = validated_data['name']
        instance.save()
        # del validated_data['specs']
        # sku = SKU.objects.create(**validated_data)
        # 对skus表进行储存
        for spec in specs:
            SKUSpecification.objects.create(sku=instance, spec_id=spec['spec_id'], option_id=spec['option_id'])
        return instance


class CategorieSerializer(serializers.ModelSerializer):
    '''
    分类序列化器
    '''

    class Meta:
        model = GoodsCategory
        fields = '__all__'


class GoodsSimpleSerializer(serializers.ModelSerializer):
    '''
    SPU序列化器
    '''

    class Meta:
        model = SPU
        fields = '__all__'


class SpecificationOptionSerializer(serializers.ModelSerializer):
    '''
        商品规格选项的序列化器
    '''

    class Meta:
        model = SpecificationOption
        fields = '__all__'


class SPUSpecificationSerializer(serializers.ModelSerializer):
    '''
    商品规格的序列化器
    '''
    spu = serializers.StringRelatedField(read_only=True)
    spu_id = serializers.IntegerField()
    # 指定规格选项返回内容
    options = SpecificationOptionSerializer(many=True)

    class Meta:
        model = SPUSpecification
        fields = '__all__'
